<template>
  <div>
    <div class="edu-page-warp">
      <condition-card @reset="reset" @search="onSubmit" label-width="120px">
        <slot>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="学院">
                <el-select v-model="queryForm.condition.collegeId" style="width:100%">
                  <el-option
                    v-for="item in source.collegeList"
                    :key="item.collegeId"
                    :label="item.collegeIdI18n"
                    :value="item.collegeId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属职级">
                <el-select v-model="queryForm.condition.title" style="width:100%">
                  <el-option
                    v-for="item in source.titleList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别">
                <el-select v-model="queryForm.condition.sex" style="width:100%">
                  <el-option
                    v-for="item in source.sexList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单位名称">
                <el-input v-model="queryForm.condition.company" style="width:100%"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单位类别">
                <el-select
                  v-model="queryForm.condition.companyType"
                  style="width:100%"
                >
                  <el-option
                    v-for="item in source.typeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="身份证号">
                <el-input v-model="queryForm.condition.idcard" style="width:100%"/>
              </el-form-item>
            </el-col>
          </el-row>
        </slot>
      </condition-card>
      <el-card shadow="never">
        <div class="edu-page-title">校外导师管理</div>
        <div class="edu-opertion-bar">
          <div class="float-left">
            <el-input
              v-model="queryForm.condition.name"
              clearable
              placeholder="请输入校外人员姓名搜索"
              style="width:200px"
              @keyup.enter.native="onSubmit"
            >
              <i
                slot="suffix"
                class="el-icon-search"
                style="margin-top:10px;cursor:pointer"
                @click="onSubmit"
              ></i>
            </el-input>
          </div>
          <div class="float-right">
            <el-dropdown @command="importRecord">
              <el-button v-if="!isAdmin">
                {{$t('message.import')}}
                <i
                  class="el-icon-arrow-down el-icon--right"
                ></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="in">{{$t('message.import')}}</el-dropdown-item>
                <el-dropdown-item command="out">{{$t('message.down')}}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button type="default" @click="exportFile()">{{$t('message.export')}}</el-button>
            <el-button type="primary" @click="addItem">{{$t('message.add')}}</el-button>
          </div>
        </div>
        <el-table
          :data="TutorList"
          size="mini"
          style="width:100%"
          @selection-change="handleSelectionChange"
          tooltip-effect="light"
        >
          <el-table-column type="selection" stripe/>
          <el-table-column show-overflow-tooltip prop="name" label="校外人员姓名" fixed="left">
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="college" label="学院" fixed="left"/>
          <el-table-column show-overflow-tooltip label="所属职级" fixed="left">
            <template slot-scope="scope">
              {{ formatTitle(scope.row) }}
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="name" label="性别" fixed="left">
            <template slot-scope="scope">{{transSex(scope.row.sex)}}</template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="name" label="身份证号" fixed="left">
            <template slot-scope="scope">{{ scope.row.idcard }}</template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="name" label="单位名称" fixed="left">
            <template slot-scope="scope">{{ scope.row.company }}</template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="name" label="职称/职务" fixed="left">
            <template slot-scope="scope">{{ scope.row.position }}</template>
          </el-table-column>
          <el-table-column show-overflow-tooltip :label="$t('label.operation')" fixed="right">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                @click="updateRecord(scope.row.id)"
              >{{$t("message.edit")}}
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click="deleteRecord(scope.row.id)"
              >{{$t("message.delete")}}
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click="viewDetail(scope.row.id)"
              >{{$t("message.detail")}}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="edu-pagination">
          <div class="float-right">
            <el-pagination
              :current-page="queryForm.pageNum_"
              :page-sizes="[20,50,100,500,1000]"
              :page-size="queryForm.pageSize_"
              :total="queryForm.total"
              layout="total, sizes, prev, pager, next, jumper"
              style="float: right;margin:10px 60px 0 0;"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
        <!--新增，编辑弹框-->
        <el-dialog
          v-if="dialogConfig.showDialog"
          :title.sync="dialogConfig.title"
          :visible.sync="dialogConfig.showDialog"
          width="70%"
          :close-on-click-modal="false"
        >
          <el-form
            :model="dialogConfig.formData"
            :rules="dialogConfig.rules"
            ref="addForm"
            label-width="130px"
          >
            <el-row hidden="hidden">
              <el-input v-model="dialogConfig.formData.id"></el-input>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="校外人员姓名" prop="name">
                  <el-input
                    v-model="dialogConfig.formData.name"
                    :disabled="flag"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号" prop="idcard">
                  <el-input
                    v-model="dialogConfig.formData.idcard"
                    :disabled="flag"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="性别" prop="sex">
                  <el-select
                    v-model="dialogConfig.formData.sex"
                    style="width:100%"
                    :disabled="flag"
                  >
                    <el-option
                      v-for="item in source.sexList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位名称" prop="company">
                  <el-input
                    v-model="dialogConfig.formData.company"
                    :disabled="isDetail"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="职称/职务" prop="position">
                  <el-input
                    v-model="dialogConfig.formData.position"
                    :disabled="isDetail"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属职级" prop="title">
                  <el-select
                    v-model="dialogConfig.formData.title"
                    :disabled="isDetail"
                    style="width:100%"
                  >
                    <el-option
                      v-for="item in source.titleList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="开户银行" prop="bankName">
                  <el-input
                    v-model="dialogConfig.formData.bankName"
                    :disabled="isDetail"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="银行卡号" prop="bankNo">
                  <el-input
                    v-model="dialogConfig.formData.bankNo"
                    :disabled="isDetail"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input
                    v-model="dialogConfig.formData.phone"
                    :disabled="isDetail"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="电子邮箱" prop="email">
                  <el-input
                    v-model="dialogConfig.formData.email"
                    :disabled="isDetail"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="是否卓越联盟" prop="isExcellent">
                  <el-select
                    v-model="dialogConfig.formData.isExcellent"
                    :disabled="isDetail"
                    style="width:100%"
                  >
                    <el-option
                      v-for="item in source.excellentList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位类别" prop="companyType">
                  <el-select
                    v-model="dialogConfig.formData.companyType"
                    :disabled="isDetail"
                    style="width:100%"
                  >
                    <el-option
                      v-for="item in source.typeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="学院" prop="collegeId">
                  <el-select v-model="dialogConfig.formData.collegeId" style="width:100%" :disabled="isDetail">
                    <el-option
                      v-for="item in source.collegeList"
                      :key="item.collegeId"
                      :label="item.collegeIdI18n"
                      :value="item.collegeId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <span slot="footer" class="dialog-footer">
                        <el-button
                          @click="closeDialog(dialogConfig)">{{$t('message.cancel')}}</el-button>
                        <el-button type="primary"
                                   @click="saveData" v-show="!isDetail">{{$t('message.save')}}</el-button>
                    </span>
        </el-dialog>
      </el-card>
    </div>
    <edu-dialog
      :title="$t('message.import')"
      size="small"
      ref="uploadDialog"
      @close="clearFiles"
      @confirm="uploadFile"
    >
      <el-form
        :model="createForm"
        ref="createForm"
        label-width="85px"
        v-loading="uploadLoading"
      >
        <el-row>
          <el-form-item>
            <el-upload
              ref="upload"
              :on-success="uploadDone"
              :auto-upload="false"
              :multiple="false"
              :on-exceed="handleExceed"
              :on-change="(file, fileList)=>{this.fileList = fileList}"
              :limit="1"
              :accept="'application/vnd.ms-excel'"
              action="/api/designservice/tutor/out/import"
            >
              <el-button
                slot="trigger"
                size="small"
                type="primary"
              >{{$t('label.selectFile')}}
              </el-button>
              <div
                slot="tip"
                class="el-upload__tip"
              >{{ $t('courseTake.uploadXLSFileOnly') }}
              </div>
            </el-upload>
            <el-button
              v-if="downShow"
              size="small"
              type="primary"
              @click="downError"
            >下载错误结果
            </el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </edu-dialog>
  </div>
</template>
<script>
  import mixin from 'common/src/mixins/index';
  import tools from 'common/src/views/underGraduationDesign/tools.js';
  import {
    addData,
    deleteData,
    downTemplate,
    editData,
    exportByPath,
    exportExcel,
    getList,
    getReportStatus,
    view
  } from 'common/src/api/underGraduationDesign/outTutor'
  import { getAllCollege } from 'common/src/api/user'

  export default {
    name: 'outTutor',
    mixins: [mixin],
    filters: {
      formatDate(date) {
        return filters.formatDate(date, 'yyyy/MM/dd hh:mm:ss')
      }
    },
    data() {
      let checkIdCard = (rule, value, callback) => {
        if (value.length != 18) {
          callback(new Error('身份证号为18位'))
          return
        }
        if (!new RegExp('^[0-9]{17}[0-9,X]$').test(value)) {
          callback(new Error('身份证号格式不对'))
        }
      }
      let checkPhone = (rule, value, callback) => {
        if (value == '') {
          callback(new Error('请输入手机号'))
          return
        }
        if (value.length > 16) {
          callback(new Error('手机号长度最多为16位'))
          return
        }
        if (!new RegExp('^[0-9]+$').test(value)) {
          callback(new Error('手机号格式不对'))
        }
      }
      let checkEmail = (rule, value, callback) => {
        if (value == '') {
          callback(new Error('请输入邮箱'))
          return
        }
        if (value.length > 16) {
          callback(new Error('邮箱长度最多为32位'))
          return
        }
        if (!new RegExp('^[0-9，a-z,A-Z]+@[0-9,a-z,A-Z,.]+$').test(value)) {
          callback(new Error('邮箱格式不对'))
        }
      }
      return {
        queryForm: {
          pageNum_: 1,
          pageSize_: 20,
          condition: {
            college: "",
            collegeId: "",
            title: "",
            sex: "",
            company: "",
            companyType: "",
            name: "",
            idcard: ""
          }
        },
        isAdmin: false,
        flag: false,
        isDetail: false,
        selectList: [],
        source: {
          collegeList: [],
          titleList: [
            {label: '正高级', value: '1'},
            {label: '副高级', value: '2'},
            {label: '中级', value: '3'},
            {label: '初级', value: '4'}
            // { label: '员级', value: '5' }
          ],
          sexList: [{label: '男', value: 1}, {label: '女', value: 2}],
          typeList: [{label: '高校', value: 1}, {label: '企事业', value: 2}],
          excellentList: [{label: '是', value: 1}, {label: '否', value: 2}]
        },
        collegeMap: {},
        TutorList: null,
        fileList: [],
        downShow: false,
        dialogConfig: {
          title: '新增校外导师',
          showDialog: false,
          formLabelWidth: '100px',
          source: {},
          formData: {
            id: null,
            name: '',
            idcard: '',
            sex: null,
            company: '',
            position: '',
            title: null,
            bankName: '',
            bankNo: '',
            phone: '',
            email: '',
            isExcellent: null,
            companyType: null,
            collegeId: '',
            college: ''
          },
          rules: {
            name: [
              {
                required: true,
                message: '请输入姓名',
                trigger: 'blur'
              },
              {
                max: 20,
                message: '长度不能超过20字符',
                trigger: 'blur'
              }
            ],
            idcard: [
              {
                required: true,
                message: '请输入身份证号',
                trigger: 'blur'
              },
              {
                validator: this.checkIdCard,
                trigger: 'blur'
              }
            ],
            sex: [
              {
                required: true,
                message: '请选择性别',
                trigger: 'change'
              }
            ],
            company: [
              {
                required: true,
                message: '请输入公司名称',
                trigger: 'blur'
              },
              {
                max: 32,
                message: '长度不能超过32字符',
                trigger: 'blur'
              }
            ],
            position: [
              {
                required: true,
                message: '请输入职位名称',
                trigger: 'blur'
              },
              {
                max: 20,
                message: '长度不能超过20字符',
                trigger: 'blur'
              }
            ],
            title: [
              {
                required: true,
                message: '请选择职级',
                trigger: 'change'
              }
            ],
            bankName: [
              {
                required: true,
                message: '请输入开户行名称',
                trigger: 'blur'
              },
              {
                max: 32,
                message: '长度不能超过32字符',
                trigger: 'blur'
              }
            ],
            bankNo: [
              {
                required: true,
                message: '请输入银行卡号',
                trigger: 'blur'
              },
              {
                max: 32,
                message: '长度不能超过32字符',
                trigger: 'blur'
              }
            ],
            phone: [
              {
                validator: this.checkPhone,
                trigger: 'blur'
              }
            ],
            email: [
              {
                validator: this.checkEmail,
                trigger: 'blur'
              }
            ],
            isExcellent: [
              {
                required: true,
                message: '请选择是否卓越联盟',
                trigger: 'change'
              }
            ],
            companyType: [
              {
                required: true,
                message: '请选择公司类型',
                trigger: 'change'
              }
            ],
            collegeId: [
            {
              required: true,
              message: '请选择学院',
              trigger: 'change'
            }
      ]
          }
        }
      }
    },
    mounted() {
      this.isAdmin = this.global.isAdmin;
      this.onSubmit()
      this.initDicts();
    },
    methods: {
      initDicts() {
        this.collegeMap = {};
        this.source.collegeList = [];
        getAllCollege(0, 1, 1).then(res => {
          res.data.forEach(item => {
            this.source.collegeList.push({
              collegeId: item.deptCode,
              collegeIdI18n: item.deptName
            });
            this.collegeMap[item.deptCode] = item.deptName;
            this.collegeMap[item.deptName] = item.deptCode;
          });
        });
      },
      formatTitle(row) {
        const filter = this.source.titleList.filter(item => item.value === row.title);
        if (filter && filter.length) {
          return filter[0].label;
        }
        return "";
      },
      reset() {
        this.queryForm.condition.title = null
        this.queryForm.condition.sex = null
        this.queryForm.condition.company = null
        this.queryForm.condition.companyType = null
        this.queryForm.condition.name = null
        this.queryForm.condition.college = ''
        this.queryForm.condition.collegeId = ''
        this.queryForm.condition.idcard = ''
        this.onSubmit()
      },
      handleSelectionChange(val) {
        this.selectList = val
      },
      onSubmit() {
        this.queryForm.condition.collegeId && (this.queryForm.condition.college = this.collegeMap[this.queryForm.condition.collegeId]);
        getList(this.queryForm).then(res => {
          if (res.code == 200) {
            this.TutorList = res.data.list
            this.queryForm.total = res.data.total
            this.selectList = []
            this.flag = false
            this.isDetail = false
          }
        })
      },
      transSex(sex) {
        if (sex == 1) {
          return '男'
        }
        return '女'
      },
      //打开新增框
      addItem() {
        this.dialogConfig.title = '新增校外导师'
        this.flag = false
        this.isDetail = false
        this.dialogConfig.formData = {
          id: null,
          name: '',
          idcard: '',
          sex: null,
          company: '',
          position: '',
          title: null,
          bankName: '',
          bankNo: '',
          phone: '',
          email: '',
          isExcellent: null,
          companyType: null,
          college: "",
          collegeId: this.global.currentUser.faculty || this.source.collegeList[0].collegeId
        }
        this.openDialog(this.dialogConfig)
      },
      //打开编辑框
      updateRecord(id) {
        this.dialogConfig.title = '编辑校外导师'
        this.flag = true
        this.isDetail = false
        view(id).then(res => {
          this.dialogConfig.formData = {
            ...res,
            collegeId: this.collegeMap[res.college]
          }
          this.openDialog(this.dialogConfig)
        })
      },
      closeDialog(dialog) {
        dialog.showDialog = false
      },
      openDialog(dialog) {
        dialog.showDialog = true
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum_ = val
        this.onSubmit()
      },
      handleSizeChange(val) {
        this.queryForm.pageSize_ = val
        this.onSubmit()
      },
      //保存
      saveData() {
        this.$refs['addForm'].validate(valid => {
          if (valid) {
            this.dialogConfig.formData.college = this.collegeMap[this.dialogConfig.formData.collegeId];
            if (
              this.dialogConfig.formData.id !== null &&
              this.dialogConfig.formData.id !== ''
            ) {
              editData(this.dialogConfig.formData).then(response => {
                if (response.code === 200) {
                  let message = this.$t('message.editSuccess')
                  this.$message({
                    type: 'success',
                    message: message
                  })
                  this.closeDialog(this.dialogConfig)
                  this.onSubmit()
                } else {
                  throw response.code
                }
              })
            } else {
              addData(this.dialogConfig.formData)
              .then(response => {
                if (response.code === 200) {
                  let message = this.$t('message.saveSuccess')
                  this.$message({
                    type: 'success',
                    message: message
                  })
                  this.closeDialog(this.dialogConfig)
                  this.onSubmit()
                } else {
                  this.$message({
                    type: 'warn',
                    message: response.message
                  })
                }
              })
              .catch(err => {
                console.log(err)
              })
            }
          }
        })
      },
      //删除
      deleteRecord(id) {
        this.$delConfirm().then(() => {
          deleteData(id).then(response => {
            if (response.code == 200) {
              this.$message({
                type: 'success',
                message: this.$t('common.tips.deleteSuccess')
              })
              this.onSubmit()
            }
          })
        })
      },
      //详情
      viewDetail(id) {
        this.dialogConfig.title = '校外导师详情'
        this.isDetail = true
        this.flag = true
        view(id).then(res => {
          if (res) {
            this.dialogConfig.formData = {
              ...res,
              collegeId: this.collegeMap[res.college]
            }
          }
          this.openDialog(this.dialogConfig)
        })

      },
      importRecord(type) {
        this.downShow = false
        if (type == 'in') {
          this.$refs.uploadDialog.open()
          // this.clearFiles();
        } else if (type == 'out') {
          downTemplate()
        }
      },
      clearFiles() {
        this.$refs.upload.clearFiles()
        this.fileList = []
      },
      uploadFile() {
        if (_.isEmpty(this.fileList)) {
          this.$message({
            type: 'warning',
            message: this.$t('message.selectFilePlease')
          })
          return
        }
        this.$refs.upload.submit()
      },
      async delayRequest(key, loading) {
        await new Promise(resolve => setTimeout(resolve, 3000))
        getReportStatus(key)
        .then(res => {
          console.info(res)
          if (res.code == 200 && res.data.status) {
            if (!res.data.success) {
              // 导入文件有错误
              let reg = new RegExp('xls')
              if (reg.test(res.data.path)) {
                this.downShow = true
                this.excelName = res.data.path
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
              loading.close()
            } else {
              this.$refs.uploadDialog.close()
              this.onSubmit()
              this.$message({
                type: 'success',
                message: this.$t('common.tips.uploadSuccess')
              })
            }
            loading.close()
          } else {
            this.delayRequest(key, loading)
          }
        })
        .catch(ex => {
          this.delayRequest(key, loading)
        })
      },
      uploadDone(res, file, fileList) {
        console.info(res)
        let loading = this.$loading({
          lock: false,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, .48)'
        })
        if (res.key) {
          this.delayRequest(res.key, loading)
        } else {
          loading.close()
          this.$message({
            type: 'warning',
            message: res.msg
          })
        }
        this.clearFiles()
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制上传文件数量为1`)
      },
      downError() {
        window.open('api/designservice/common/export?path=' + this.excelName)
        this.downShow = false
      },
      exportFile() {
        var data = {
          vo: this.queryForm.condition,
          list: this.selectList
        }
        exportExcel(data).then(res => {
          tools.downloadFile(res.data.key, "校外导师.xls", null, this);
          /*let loading = this.$loading({
              lock: false,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(255, 255, 255, .48)'
          })
          if (res.code === 200) {
              this._delayRequest(res.data.key, loading)
          } else {
              loading.close()
          }*/
        })
      },
      async _delayRequest(key, loading) {
        await new Promise(resolve => setTimeout(resolve, 3000))
        getReportStatus(key)
        .then(res => {
          if (res.code == 200 && res.data.status) {
            let path = 'api/majorservice/common/export?path=' + res.data.path
            window.open(path)
            loading.close()
          } else {
            this._delayRequest(key, loading)
          }
        })
        .catch(ex => {
          this._delayRequest(key, loading)
        })
      }
    }
  }
</script>
